<?php
/*
Plugin Name: WooCommerce - Post-Purchase Follow-ups
Plugin URI: http://ignitewoo.com
Description: <strong>IgniteWoo.com</strong> - Automatically sends customizable messages to customers
Version: 1.9.4
Author: IgniteWoo.com
Author URI: http://ignitewoo.com
License: COMMERCIAL CODE - SINGLE SITE LICENSE - THIS IS NOT GPL CODE
*/

/**

Copyright (c) 2012 - IgniteWoo.com - All Rights Reserved

YOU MAY NOT USE THIS CODE WITHOUT BUYING A LICENSE FOR EACH SITE THAT YOU INTEND TO USE IT ON/

USE THIS SOFTWARE AT YOUR OWN RISK. NO WARRANTY IS EXPRESSED NOR IMPLIED. 

*/

/** 

    NOTE: Is there are a way to do conversion tracking somehow? 

    TODO: Handle "bounces" somehow? Or just let the store operator handle those manually via their return-email-address inbox? 


*/

/**
* Required functions
*/
if ( ! function_exists( 'ignitewoo_queue_update' ) )
	require_once( dirname( __FILE__ ) . '/ignitewoo_updater/ignitewoo_update_api.php' );

$this_plugin_base = plugin_basename( __FILE__ );

add_action( "after_plugin_row_" . $this_plugin_base, 'ignite_plugin_update_row', 1, 2 );


/**
* Plugin updates
*/
ignitewoo_queue_update( plugin_basename( __FILE__ ), '88e50db2aad01620a329d6bcb0775562', '318' );


class woocommerce_post_sale_followup { 

	var $plugin_url = '';

	var $email_recipient = '';

	var $skips = false;

	var $current_msg = false;

	var $is_followup = false;

	function __construct() { 

		add_action( 'init', array( &$this, 'register_post_type' ), 99999999 );

		add_action( 'init', array( &$this, 'followup_img' ), -9999 );

		add_action( 'init', array( &$this, 'followup_clk' ), -9999 );

		add_action( 'init', array( &$this, 'handle_unsubs' ), 1 );

		add_action( 'init', array( &$this, 'software_tests' ), -1 );

		add_filter( 'woocommerce_settings_tabs_array', array( &$this, 'add_tab' ), 1, 1 );

		add_action( 'woocommerce_settings_tabs_post_sale_email', array( &$this, 'post_sale_email_box' ) );

		add_action( 'woocommerce_update_options_post_sale_email',  array( &$this, 'save_settings' ) );

		//add_action( 'admin_footer', array( &$this, 'help' ) );

		add_action( 'admin_enqueue_scripts', array( &$this, 'add_scripts' ), 999999 );

		add_action( 'admin_print_styles', array( &$this, 'admin_styles' ), 999999 );

		add_action( 'add_meta_boxes', array( &$this, 'metaboxes' ) );

		add_filter( 'enter_title_here', array( &$this, 'enter_title_here' ), 1, 2 );

		add_action( 'save_post', array( &$this, 'save_post' ) );

		add_action( 'manage_shop_followup_posts_custom_column', array( &$this, 'custom_coupon_columns' ), 2);

		add_filter( 'manage_edit-shop_followup_columns', array( &$this, 'edit_coupon_columns' ) );

		add_filter( 'manage_edit-shop_followup_sortable_columns',  array( &$this,'shop_followup_sortable_columns' ) );

		add_filter( 'requests', array( &$this, 'shop_followup_column_sorting' ) );

		add_filter( 'the_editor_content', array( &$this, 'load_template' ) );

		add_action( 'admin_head', array( &$this, 'addbuttons' ) );

		add_action( 'hourly_event', array( &$this, 'do_hourly' ) );

		add_action( 'daily_event', array( &$this, 'do_daily' ) );

		add_action( 'woocommerce_new_order', array( &$this, 'add_followup_meta' ), -1, 1 );

		add_action( 'woocommerce_add_to_cart', array( &$this, 'add_to_cart' ), 35 );

		add_action( 'woocommerce_simple_add_to_cart', array( &$this, 'add_to_cart' ), 35 );

		add_action( 'woocommerce_grouped_add_to_cart', array( &$this, 'add_to_cart' ), 35 );

		add_action( 'woocommerce_variable_add_to_cart', array( &$this, 'add_to_cart' ), 35 );

		add_action( 'woocommerce_external_add_to_cart', array( &$this, 'add_to_cart' ), 35 );

		add_filter( 'woocommerce_email_footer', array( &$this, 'build_mail_footer' ), 5, 1 );

		add_action( 'wp_ajax_ignite_json_search_coupons', array( &$this, 'json_search_products_and_variations' ) );

		add_action( 'wp_ajax_ignite_follow_test_msg', array( &$this, 'ignite_follow_test_msg' ) );

		$this->plugin_url = WP_PLUGIN_URL . '/' . str_replace( basename( __FILE__ ), '' , plugin_basename( __FILE__ ) ); 

		$this->email_recipient = '';

		$this->skips = false;

		$this->current_msg = false;

		$this->is_followup = false;

	}


	// Make sure the site is running WooCommerce 1.5 or later
	function software_tests() { 
		global $woocommerce;

		if ( !$woocommerce ) 
			return;

		if ( version_compare( $woocommerce->version, '1.5.0' ) <= 0 )
			add_action( 'admin_notices', array( &$this, 'version_nag' ) );

		if ( !file_exists( WP_PLUGIN_DIR . '/woocommerce/admin/post-types/writepanels/writepanel-coupon_data.php' ) ) 
			add_action( 'admin_notices', array( &$this, 'update_nag' ) );

	}


	function version_nag() { 
		global $woocommerce;

		echo '<div style="background-color:#cf0000;color:#fff;font-weight:bold;font-size:16px;margin: -1px 15px 0 5px;padding:5px 10px">';

		_e( 'The WooCommerce Gift Certificates Pro plugin requires WooCommerce 1.5.0 or newer to work correctly. You\'re using version', 'woocommerce' );

		echo ' ' . $woocommerce->version; 

		echo '</div>';

	}


	function update_nag() { 
		global $woocommerce;

		echo '<div style="background-color:#cf0000;color:#fff;font-weight:bold;font-size:16px;margin: -1px 15px 0 5px;padding:5px 10px">';

		_e( 'Some required core WooCommerce files are no longer present. The WooCommerce Post-Purchase Follow-up plugin needs an update!', 'woocommerce' );

		echo ' ' . $woocommerce->version; 

		echo '</div>';

	}


	function add_tab( $tabs = '' ) { 

		$tabs['post_sale_email'] = __( 'Post-Purchase Email', 'woocommerce' );

		return $tabs;

	}


	function post_sale_email_box() { 

		$footer = get_option( 'woocommerce_followup_footer', false );

		$title = get_option( 'woocommerce_followup_title', false );

		$body = get_option( 'woocommerce_followup_body', false );

		$abandoned_cleanup_delay = get_option( 'abandoned_cleanup_delay', false );

		if ( !$abandoned_cleanup_delay ) 
			$abandoned_cleanup_delay = 14;

		?>


		<p><?php _e( 'To comply with various US and International anti-spam laws you should define a footer in the box below.', 'woocommerce' ) ?></p>

		<p><?php _e( 'The information should typically include at least your store name, address, and phone number.', 'woocommerce' ) ?></p>

		<p><?php _e( 'The information will be appended to bottom of all messages sent by the Post-Purchase Follow-up plugin', 'woocommerce' ) ?></p>

		<p><?php _e( 'An unsubscribe link will also be added automatically. After a customer unsubscribes they will not receive any more follow-up email messages.', 'woocommerce' ) ?></p>

		<div>
			<table class="form-table">
			<tbody>
				<tr valign="top">
					<th class="titledesc" scope="row">
						<label for="woocommerce_new_order_email_recipient"><?php _e( 'Contact Info', 'woocommerce' )?></label>
					</th>
				  
					<td class="forminp">
						<textarea style="width:100%; height: 75px;" placholder="<?php _e('Enter your store name, address and phone number', 'woocommerce' )?>" name="store_followup_footer"><?php echo $footer ?></textarea>
					</td>
				</tr>

				<tr valign="top">
					<th class="titledesc" scope="row">
						<label for="woocommerce_new_order_email_recipient"><?php _e( 'Unsubscribe Page Title', 'woocommerce' )?></label>
						    <img class="help_tip" data-tip='<?php _e('The title shown on the screen when someone unsubscribes.', 'woocommerce') ?>' 
						    src="<?php echo $this->plugin_url; ?>/help.png" /><br/>
					</th>
				  
					<td class="forminp">
						<input type="text" style="width:100%;" name="store_followup_title" value="<?php echo $title ?>">
					</td>
				</tr>

				<tr valign="top">
					<th class="titledesc" scope="row">
						<label for="woocommerce_new_order_email_recipient"><?php _e( 'Unsubscribe Page Content', 'woocommerce' )?></label>
						    <img class="help_tip" data-tip='<?php _e('The message shown on the screen when someone unsubscribes.', 'woocommerce') ?>' 
						    src="<?php echo $this->plugin_url; ?>/help.png" /><br/>

					</th>
				  
					<td class="forminp">
						<textarea style="width:100%; height: 75px;" name="store_followup_body"><?php echo $body ?></textarea>
					</td>
				</tr>

				<tr valign="top">
					<th class="titledesc" scope="row">
						<label for="woocommerce_new_order_email_recipient"><?php _e( 'Abandonemt clean-up delay', 'woocommerce' ) ?></label>
							<img class="help_tip" data-tip='<?php _e('The delay (in days) before abandoned carts are discarded from follow-up message processing (This does not effect the WooCommerce persistent cart contents). The default is 14.', 'woocommerce') ?>' 
							src="<?php echo $this->plugin_url; ?>/help.png" /><br/>
					</th>
					<td>
						<input type="text" name="abandoned_cleanup_delay" value="<?php echo $abandoned_cleanup_delay ?>" style="width: 40px"> <?php _e( 'days', 'woocommerce' )?>
					</td>

			</tbody>
			</table>

		</div>


		<?php
	}


	function save_settings() {

		if ( isset( $_POST['store_followup_footer'] ) )
			update_option( 'woocommerce_followup_footer', $_POST['store_followup_footer'] );
		else
			update_option( 'woocommerce_followup_footer', '' );

		if ( isset( $_POST['store_followup_title'] ) )
			update_option( 'woocommerce_followup_title', $_POST['store_followup_title'] );
		else
			update_option( 'woocommerce_followup_footer', '' );

		if ( isset( $_POST['store_followup_body'] ) )
			update_option( 'woocommerce_followup_body', $_POST['store_followup_body'] );
		else
			update_option( 'woocommerce_followup_body', '' );

		if ( !isset( $_POST['abandoned_cleanup_delay'] ) || '' == trim( $_POST['abandoned_cleanup_delay'] ) )
			$_POST['abandoned_cleanup_delay'] = 14;

		update_option( 'abandoned_cleanup_delay', intval( $_POST['abandoned_cleanup_delay'] ) );

	}



	function metaboxes() { 

		add_meta_box( 'woocommerce-followup-data-test', __( 'Test Message', 'woocommerce' ), array( &$this, 'post_screen_test' ), 'shop_followup', 'normal', 'default');

		add_meta_box( 'woocommerce-followup-data', __( 'Follow-up Settings', 'woocommerce' ), array( &$this, 'post_screen' ), 'shop_followup', 'normal', 'default');

		if ( !function_exists('woocommerce_coupon_data_meta_box') ) 
			require_once( WP_PLUGIN_DIR . '/woocommerce/admin/post-types/writepanels/writepanel-coupon_data.php');

		add_meta_box( 'woocommerce-followup-coupon-data', __('Coupon Data', 'woocommerce'), 'woocommerce_coupon_data_meta_box', 'shop_followup', 'normal', 'default');

		// add_meta_box( 'woocommerce-followup-help', __( 'Post-Purchase Help', 'woocommerce' ), array( &$this, 'help_button' ), 'shop_followup', 'side', 'high');

		add_meta_box( 'woocommerce-followup-ignitewoo', __( 'Hey!', 'woocommerce' ), array( &$this, 'iw_side' ), 'shop_followup', 'side', 'high');

		remove_meta_box( 'woothemes-settings', 'shop_followup' , 'normal' );

		remove_meta_box( 'commentstatusdiv', 'shop_followup' , 'normal' );

		remove_meta_box( 'slugdiv', 'shop_followup' , 'normal' );

	}


	function enter_title_here( $text, $post ) {

		if ($post->post_type=='shop_followup') 
			return __('Follow-up Message Title', 'woocommerce');

		return $text;
	}


	function admin_styles() { 
		global $woocommerce; 

		if ( !function_exists('woocommerce_admin_init') ) 
			require_once( dirname( __FILE__ ) . '/../woocommerce/admin/woocommerce-admin-init.php');

		wp_enqueue_style( 'woocommerce_admin_styles', $woocommerce->plugin_url() . '/assets/css/admin.css' );

		wp_enqueue_style( 'jquery-ui-style', (is_ssl()) ? 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' : 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' );

	}

	// This function is based partially on core WooCommerce code: 
	function add_scripts() {
		global $woocommerce, $post;

		if ( 'shop_followup' != $post->post_type ) 
			return;

		if ( !function_exists('woocommerce_admin_init') ) 
			require_once( dirname( __FILE__ ) . '/../woocommerce/admin/woocommerce-admin-init.php');

		wp_enqueue_script( 'woocommerce_admin');
		wp_enqueue_script( 'woocommerce_writepanel' );
		wp_enqueue_script( 'jquery-ui-datepicker' );
		wp_enqueue_script( 'media-upload' );
		wp_enqueue_script( 'thickbox' );
		wp_enqueue_script( 'ajax-chosen' );
		wp_enqueue_script( 'chosen' );

		$woocommerce_witepanel_params = array( 
			'remove_item_notice' 				=> __("Remove this item? If you have previously reduced this item's stock, or this order was submitted by a customer, will need to manually restore the item's stock.", 'woocommerce'),
			'remove_attribute'				=> __('Remove this attribute?', 'woocommerce'),
			'name_label'					=> __('Name', 'woocommerce'),
			'remove_label'					=> __('Remove', 'woocommerce'),
			'click_to_toggle'				=> __('Click to toggle', 'woocommerce'),
			'values_label'					=> __('Value(s)', 'woocommerce'),
			'text_attribute_tip'				=> __('Enter some text, or some attributes by pipe (|) separating values.', 'woocommerce'),
			'visible_label'					=> __('Visible on the product page', 'woocommerce'),
			'used_for_variations_label'			=> __('Used for variations', 'woocommerce'),
			'calc_totals' 					=> __("Calculate totals based on order items, discount amount, and shipping? Note, you will need to (optionally) calculate tax rows and cart discounts manually.", 'woocommerce'),
			'calc_line_taxes' 				=> __("Calculate line taxes? This will calculate taxes based on the customers country. If no billing/shipping is set it will use the store base country.", 'woocommerce'),
			'copy_billing' 					=> __("Copy billing information to shipping information? This will remove any currently entered shipping information.", 'woocommerce'),
			'load_billing' 					=> __("Load the customer's billing information? This will remove any currently entered billing information.", 'woocommerce'),
			'load_shipping' 				=> __("Load the customer's shipping information? This will remove any currently entered shipping information.", 'woocommerce'),
			'tax_or_vat'					=> $woocommerce->countries->tax_or_vat(),
			'prices_include_tax' 				=> get_option('woocommerce_prices_include_tax'),
			'round_at_subtotal'				=> get_option( 'woocommerce_tax_round_at_subtotal' ),
			'meta_name'					=> __('Meta Name', 'woocommerce'),
			'meta_value'					=> __('Meta Value', 'woocommerce'),
			'no_customer_selected'				=> __('No customer selected', 'woocommerce'),
			'tax_label'					=> __('Tax Label:', 'woocommerce'),
			'compound_label'				=> __('Compound:', 'woocommerce'),
			'cart_tax_label'				=> __('Cart Tax:', 'woocommerce'),
			'shipping_tax_label'				=> __('Shipping Tax:', 'woocommerce'),
			'plugin_url' 					=> $woocommerce->plugin_url(),
			'ajax_url' 					=> admin_url('admin-ajax.php'),
			'add_order_item_nonce' 				=> wp_create_nonce("add-order-item"),
			'calc_totals_nonce' 				=> wp_create_nonce("calc-totals"),
			'get_customer_details_nonce' 			=> wp_create_nonce("get-customer-details"),
			'search_products_nonce'				=> wp_create_nonce("search-products"),
			'calendar_image'				=> $woocommerce->plugin_url().'/assets/images/calendar.png',
			'post_id'					=> $post->ID
		 );
					 
		wp_localize_script( 'woocommerce_writepanel', 'woocommerce_writepanel_params', $woocommerce_witepanel_params );

		wp_enqueue_script( 'common' );

		wp_enqueue_script( 'jquery-color' );

		wp_print_scripts('media-upload');

		?>
		<script>

			jQuery( document ).ready( function() { 

				<?php if ( '1' != get_post_meta( $post->ID, 'generate_coupon', true ) ) { ?>

				jQuery( '#woocommerce-followup-coupon-data' ).hide( 'fast' );

				<?php } ?>


				jQuery( '#generate_coupon' ).click( function() { 

					jQuery( '#woocommerce-followup-coupon-data' ).toggle('fast');

				});

				a = '<label for="expiry_date"><?php _e('Validity Timeframe', 'woocommerce')?></label><input type="text" placeholder="<?php _e('Never expire', 'woocommerce')?>" value="<?php echo get_post_meta( $post->ID, 'expiry_date', true) ?>" id="expiry_date" name="expiry_date" class="short"><span class="description"><?php _e('How many days after issuance is this coupon valid?', 'woocommerce')?></span>';

				jQuery( '.expiry_date_field').html( a );

				jQuery( '.date-picker' ).datepicker( { dateFormat: 'mm-dd' } );

				/******
				jQuery( '#followup_help_button' ).click( function() { 
					jQuery('#post-body-content').hide()
					temp = jQuery('#followup_help_content').html();
					jQuery('#post-body').append( '<div id="temp_help">' + temp + '</div>' ); 
				});
				*******/

				jQuery("select.ajax_chosen_select_coupons").ajaxChosen({
				    method: 	'GET',
				    url: ajaxurl,
				    dataType: 	'json',
				    afterTypeDelay: 100,
				    data: {
						action: 'ignite_json_search_coupons',
						security: woocommerce_writepanel_params.search_products_nonce
				    }
				}, function (data) {
				
					var terms = {};
					
				    jQuery.each(data, function (i, val) {
					terms[i] = val;
				    });
				
				    return terms;
				});

				jQuery( "#ignite_followup_send_test" ).click( function() { 

					var em = jQuery( "#ignite_send_followup_test_msg").val();

					if ( null == em || 0 == em.length ) {
						alert( "<?php _e( 'Enter an email address first!','woocommerce' )?>" );
						return false;
					}

					var t = jQuery( "#title", "#titlewrap" ).val();

					if ( null == t || 0 == t.length ) {
						alert( "<?php _e( 'Enter a message title first!','woocommerce' )?>" );
						return false;
					}


					if ( jQuery( "#content").is(":visible") )
						var icontent = jQuery( "#content").val();
					else 
						var icontent = jQuery( "#content_ifr").contents().find( "body#tinymce" ).html();

					if ( null == icontent || 0 == icontent.length ) {
						alert( "<?php _e( 'Enter some message content first!','woocommerce' )?>" );
						return false;
					}

					ttype = jQuery( ".trigger_type:checked" ).val();

					if ( null == ttype || 0 == ttype.length ) {
						alert( "<?php _e( 'Select a trigger type first!','woocommerce' )?>" );
						return false;
					}


					jQuery.post( ajaxurl, { action: "ignite_follow_test_msg", t: t, tt: ttype, em: em, c: icontent, n: woocommerce_writepanel_params.search_products_nonce }, function( data ) { 
						if ( "ok" !== data ) 
							alert( "<?php _e( 'There was an error sending your test message!','woocommerce' )?>\n\n" + data );
						else
							alert( "<?php _e( 'Message sent!','woocommerce' )?>" );  
					});

					return false;

				});

			}); 

		</script>
		<?php

	}


	function addbuttons() {
		global $post_type;

		if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) )
			return;

		if ( 'shop_followup' != $post_type ) 
			return;
		
		if ( get_user_option( 'rich_editing' ) == 'true') {

			add_filter( 'mce_external_plugins', array( &$this, 'add_tinymce_plugin' ) );

			add_filter( 'mce_buttons', array( &$this, 'register_button' ) );
		}

	}
	

	function register_button( $buttons ) {

		array_push( $buttons, 'separator', 'followup' );

		return $buttons;
	}

	
	function add_tinymce_plugin($plugin_array) {
		global $post_type; 

		if ( 'shop_followup' != $post_type ) 
			return $plugin_array;

		$plugin_array['followup'] = $this->plugin_url . 'followup_plugin.js';

		return $plugin_array;
	}


	/*
	function help_button() { 
		?>
		<p><input id="followup_help_button" type="button" style="border: 2px solid #000" name="followup_help" value="Show Post-Purchase Follow-up Help" class="button"></p>
		<?php
	}


	function help() { 

	    ?>
		    <div id="followup_help_content" style="display:none; margin-right: 300px;">

				<p>
					<input class="followup_help_close button" type="button" name="followup_help" value="Close Help">
				</p>

				<h2><strong><?php _e( 'Important Notes', 'woocommerce' )?></strong></h2>

				<div style="clear:both">

					<p><?php _e( 'All email messages are sent to the BILLING contact listed in a given shop order.', 'woocommerce' ) ?></p>

					<p><?php _e( 'Products and product definitions are not applicable to abandoned cart triggers.', 'woocommerce' ) ?></p>

					<p><?php _e( 'If you enable the message to generate coupons then one new coupon will created for every customer who receives the message.', 'woocommerce' ) ?></p>

					<p><?php _e( 'For support and other matters contact us via our Web site.', 'woocommerce' ) ?></p>


				</div>

				<script>
					jQuery( '.followup_help_close' ).click( function() {  
						jQuery( '#temp_help' ).remove();
						jQuery( '#post-body-content' ).show();
					});
				</script>
		    </div>
	    <?php

	}
	*/

	function load_template( $content = '' ) { 
		global $post;

		if ( 'shop_followup' != $post->post_type )
			return $content;

		if ( '' != $content ) 
			return $content;

		$template = locate_template( array( 'emails/base-followup-template.php' ), false, false );

		if ( '' != $template ) 
			$template = file_get_contents( $template );
		else 
			$template = file_get_contents( dirname( __FILE__ ) . '/emails/base-followup-template.php' );

		return $template;

	}


	function ignite_follow_test_msg() { 
		global $woocommerce; 

		$this->is_followup = true;

		check_ajax_referer( 'search-products', 'n' );

		if ( '' == trim( $_POST['em'] ) || '' == trim( $_POST['c'] ) || '' == trim( $_POST['t'] ) || '' == trim( $_POST['tt'] ) )
			die;

		if ( !is_email( $_POST['em'] ) )
			die( __( 'That is not a valid email address!','woocommerce' ) );

		$message = $this->filter_tags( $_POST['c'], 'JUL12-A1B2C3D4 <br/> JUL12-E5F6G7H8', $_POST['em'], __( 'John', 'woocommerce' ), __( 'Doe', 'woocommerce' ) );

		$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

		$subject = sprintf( __( '[%s] %s', 'woocommerce' ), $blogname, $subject );

		global $cart_items, $followup_content, $email_heading;

		$cart_items = array();

		$cart_items[] = array(
				'name' => '<a href="' . get_option( 'home' ) . '">' . __( 'Test Product</a>', 'woocommerce' ) . '</a>',
				'price' => '1.00',
				'qty' => '2', 
				'item_total' => get_woocommerce_currency_symbol() . '2.00'
		);

		$followup_content = $message; 

		$email_heading = $subject;

		if ( 'abandoned' == $_POST['tt'] ) 
			$template_name = 'emails/abandoned_cart.php';
		else
			$template_name = 'emails/followup_email_template.php';


		$default_path = dirname( __FILE__ ) . '/';

		ob_start();

		$located = woocommerce_locate_template( $template_name, $template_path, $default_path );

		if ( $located ) { 

			do_action( 'woocommerce_before_template_part', $template_name, '', $located );

			require( $located );

			do_action( 'woocommerce_after_template_part', $template_name, '', $located );

		} else {

			ob_end_clean();

			return;

		}

		$msg = ob_get_clean();

		$this->is_followup = false;

		// Queue additional mail envelope headers
		$headers = apply_filters('woocommerce_email_headers', '', 'followup_message');

		if ( !$woocommerce->woocommerce_email ) 
			$woocommerce->mailer();

		$woocommerce->woocommerce_email->send( $_POST['em'], $_POST['title'], $msg, $headers );

		die( 'ok' );

	}


	//  This function is based on core WooCommerce code
	function json_search_products_and_variations( $x = '', $post_types = array('shop_coupon') ) {

		check_ajax_referer( 'search-products', 'security' );
		
		$term = (string) urldecode(stripslashes(strip_tags($_GET['term'])));
		
		if (empty($term)) die();
		
		if ( is_numeric( $term ) ) {
			
			$args = array(
				'post_type'		=> $post_types,
				'post_status'	 	=> 'publish',
				'posts_per_page' 	=> -1,
				'post__in' 		=> array(0, $term),
				'fields'		=> 'ids'
			);
			
			$args2 = array(
				'post_type'		=> $post_types,
				'post_status'	 	=> 'publish',
				'posts_per_page' 	=> -1,
				'post_parent' 		=> $term,
				'fields'		=> 'ids'
			);
			
			$posts = array_unique(array_merge( get_posts( $args ), get_posts( $args2 ) ));
			
		} else {
		
			$args = array(
				'post_type'		=> $post_types,
				'post_status' 		=> 'publish',
				'posts_per_page' 	=> -1,
				's' 			=> $term,
				'fields'		=> 'ids'
			);
			
			$args2 = array(
				'post_type'		=> $post_types,
				'post_status' 		=> 'publish',
				'posts_per_page' 	=> -1,
				'meta_query' 		=> array(
					array(
					'key' 	=> '_sku',
					'value' => $term,
					'compare' => 'LIKE'
					)
				),
				'fields' => 'ids'
			);
			
			$posts = array_unique(array_merge( get_posts( $args ), get_posts( $args2 ) ));

		}
		
		$found_products = array();

		if ($posts) foreach ($posts as $post) {
			
			$found_products[$post] = get_the_title( $post ) . ' &ndash; #' . $post;
			
		}
		
		echo json_encode( $found_products );
		
		die;
	}


	function post_screen_test() {
		?>
			<table style="width:99%;margin:0;padding:0">
				<tr>
					<td style="width:20%; vertical-align:top">
						<label for="logo_image"><?php _e( 'Send a test message', 'woocommerce' ) ?></label>
					</td>
					<td style="vertical-align:top; padding-bottom: 25px">
							<p><?php _e( 'To preview your message enter an email address below and click Send Message.' ) ?></p>
							<p><?php _e( 'Note that any randomly generated coupon codes will be fake for purpooses of testing.' ) ?></p>
							<?php _e( 'Email address: ', 'woocommerce' ) ?> <input id="ignite_send_followup_test_msg" type="text" name="ignite_send_followup_test_msg" value=""> 
							<input type="submit" name="submit" id="ignite_followup_send_test" class="button-primary" value="<?php _e('Send Message', 'woocommerce' )?>">
					</td>
				</tr>
			</table>
		<?php 
	}


	function post_screen() { 
		global $post;

		$type = get_post_meta( $post->ID, 'followup_type', true );

		$days = get_post_meta( $post->ID, 'post_followup_days', true );

		$header_img = get_post_meta( $post->ID, 'post_followup_header', true );

		$footer_img = get_post_meta( $post->ID, 'post_followup_footer', true );

		$gen_coupon = get_post_meta( $post->ID, 'generate_coupon', true );

		$restrict_coupon = get_post_meta( $post->ID, 'restrict_coupon', true );

		$send_on_date = get_post_meta( $post->ID, 'send_on_date', true );

		$coupon_prefix = get_post_meta( $post->ID, 'coupon_prefix', true );

		$prod_ids = get_post_meta( $post->ID, 'prod_ids', true );

		$cat_ids = (array) get_post_meta( $post->ID, 'prod_categories', true );

		$coupon_ids = get_post_meta( $post->ID, 'coupon_ids', true );

		$tracker = get_post_meta( $post->ID, 'tracker_code', true );

		$abandoned_delay = get_post_meta( $post->ID, 'abandoned_delay', true );

		if ( !$abandoned_delay ) 
			$abandoned_delay = 3;


		if ( $tracker ) 
			$tracker = stripslashes( $tracker );

		?>

			<style>#send_after_date, #send_on_date { width: 200px; }</style>

			<script>
				jQuery( document ).ready( function() { 
					jQuery( '.customer_email_field' ).hide('fast');
				});
			</script>

			<table style="width:99%;margin:0;padding:0">

				<tr>
					<td style="width:20%; vertical-align:top">
						<label for="logo_image"><?php _e( 'Interval', 'woocommerce' ) ?></label>
					</td><td style="vertical-align:top; padding-bottom: 25px">
						<?php _e('Select message trigger:', 'woocommerce')?>
						    <img class="help_tip" data-tip='<?php _e('Select the interval to send this message.', 'woocommerce') ?>' 
						    src="<?php echo $this->plugin_url; ?>/help.png" /><br/>

						<p><input class="trigger_type" <?php if ( 'buyer' == $type ) echo 'checked="checked"' ?> type="radio" name="followup_type" value="buyer"> <?php _e(' To a buyer', 'woocommerce')?> <input type="text" name="post_followup_days" value="<?php echo $days ?>" length="3" style="width: 32px" > <?php _e(' days after they make a purchase.', 'woocommerce')?></p>
						<p><input class="trigger_type" <?php if ( 'on_date' == $type ) echo 'checked="checked"' ?> type="radio" name="followup_type" value="on_date"> <?php _e('To all buyers on this day of the year:', 'woocommerce')?><?php woocommerce_wp_text_input( array( 'id' => 'send_on_date', 'label' => __('', 'woocommerce'), 'placeholder' => '', 'description' => '', 'class' => 'short date-picker' ) ); ?><?php _e('Enter the date as','woocommerce' )?> <code>MM-DD</code> </p>
						<p><input class="trigger_type" <?php if ( 'first_anniversary' == $type ) echo 'checked="checked"' ?> type="radio" name="followup_type" value="first_anniversary"> <?php _e('On the yearly anniversary of the first purchase of each buyer.', 'woocommerce')?></p>
						<p><input class="trigger_type" <?php if ( 'every_anniversary' == $type ) echo 'checked="checked"' ?> type="radio" name="followup_type" value="every_anniversary"> <?php _e('On the yearly anniversary of every purchase of each buyer.', 'woocommerce')?></p>

						<p><?php _e( 'AND', 'woocommerce' )?>
						    <img class="help_tip" data-tip='<?php _e('Optionally refine who receives this message by selecting products that must be purchased, or product categories that must have been part of the purchase. NOTE: This does not apply to abandoned cart messages!', 'woocommerce') ?>' 
						    src="<?php echo $this->plugin_url; ?>/help.png" /></p>

						<p><?php _e( 'The buyer purchases any of the following product(s):', 'woocommerce' )?><br/>

							<select id="prod_ids" name="prod_ids[]" class="ajax_chosen_select_products_and_variations" multiple="multiple" data-placeholder="<?php _e('Search for a product&hellip;', 'woocommerce'); ?>" style="width: 400px">
								<?php
									if ( $prod_ids ) {

										$prod_ids = explode( ',', $prod_ids );

										$prod_ids = array_unique( $prod_ids );

										foreach ( $prod_ids as $product_id ) {

											$title  = get_the_title( $product_id );

											$sku    = get_post_meta( $product_id, '_sku', true );
											
											if ( !$title ) continue;
							
											if (isset( $sku ) && $sku ) $sku = ' (SKU: ' . $sku . ')';
							
											echo '<option value="'.$product_id.'" selected="selected">'. $title . $sku .'</option>';
										}
									}
								?>
							</select>
						<p>


						<p><?php _e( 'The buyer purchases products in any of the following categories:', 'woocommerce' )?><br/>

							<select id="prod_categories" name="prod_categories[]" class="chosen_select" multiple="multiple" data-placeholder="<?php _e('Any category', 'woocommerce'); ?>"  style="width: 400px">

								<?php
									
									$categories = get_terms( 'product_cat', 'orderby=name&hide_empty=0' );

									if ( $categories ) 
									foreach ( $categories as $cat ) {

										echo '<option value="'.$cat->term_id.'"';

										if ( in_array( $cat->term_id, $cat_ids ) ) echo 'selected="selected"';

										echo '>'. $cat->name .'</option>';
									}
								?>
							</select>
						</p>

						<p>
							<input class="trigger_type" <?php if ( 'abandoned' == $type ) echo 'checked="checked"' ?> type="radio" name="followup_type" value="abandoned"> <?php _e('When a shopper abandons their cart.', 'woocommerce')?>
							<img class="help_tip" data-tip='<?php _e('Send this message when a shopper abandons their cart. Carts are tracked for logged in customers only. Carts are considered abandoned after 24 hours, which will trigger this message if this trigger option is selected. NOTE: Records of abandoned carts are deleted after 14 days! Optionally use the red Followup Tags icon in the visual editor to insert a tag into the message that shows the customer their cart contents.', 'woocommerce') ?>' 
							src="<?php echo $this->plugin_url; ?>/help.png" /><br/>
						</p>

						<p>
						<?php _e( 'Abandonemt message delay', 'woocommerce' ) ?>
						<input type="text" name="abandoned_delay" value="<?php echo $abandoned_delay ?>" style="width: 40px"> <?php _e( 'days', 'woocommerce' )?>
							<img class="help_tip" data-tip='<?php _e('The delay (in days) before a cart is considered abandoned which triggers this message to be sent. The default is 3.', 'woocommerce') ?>' 
							src="<?php echo $this->plugin_url; ?>/help.png" /><br/>
						</p>

					</td>
				</tr>

				<tr>
					<td style="width:20%; vertical-align:top">
						<label for="footer_image"><?php _e( 'Attach Coupons', 'woocommerce' ) ?></label>
					</td>

					<td style="vertical-align:top; padding-bottom: 5px">

						<p>
						<input type="checkbox" <?php if ( '1' == $gen_coupon ) echo 'checked="checked"' ?> name="gen_coupon" value="1" id="generate_coupon" class="text_input"/>  
						<?php _e( 'Generate new coupon', 'woocommerce' )?>
						    <img class="help_tip" data-tip='<?php _e('Automatically generate a unique random coupon code for each customer and send it with this message.', 'woocommerce') ?>' 
						    src="<?php echo $this->plugin_url; ?>/help.png" /><br/>
						</p>

						<p>
						<input type="checkbox" <?php if ( '1' == $restrict_coupon ) echo 'checked="checked"' ?> name="restrict_coupon" value="1" id="generate_coupon" class="text_input"/>  
						<?php _e( 'Automatically restrict generated coupons to the customer.', 'woocommerce' )?>
						    <img class="help_tip" data-tip='<?php _e( "This causes generated coupons to be automatically tied to the customer email address so that the shopper email must match the email address that the coupon was sent to before the shopper can use the coupon code.", 'woocommerce') ?>' 
						    src="<?php echo $this->plugin_url; ?>/help.png" /><br/>
						</p>

						<p><?php _e( '<em>Optional:</em> Set a prefix for randonly generated coupons. Keep it short! If you leave this blank the current month and year will be used as the default (example: JAN12)', 'woocommerce' ) ?></p>
						<?php _e( 'Coupon Prefix:', 'woocommerce' ) ?><input type="text" name="coupon_prefix" value="<?php echo $coupon_prefix ?>">
						</p>

						<p><?php _e( 'You can also select existing coupons to send with this message.', 'woocommerce' ) ?></p>
							<select id="coupon_ids" name="coupon_ids[]" class="ajax_chosen_select_coupons" multiple="multiple" data-placeholder="<?php _e('Search for a coupon by title&hellip;', 'woocommerce'); ?>" style="width: 400px">
								<?php
									if ( $coupon_ids ) {

										$coupon_ids = explode( ',', $coupon_ids );

										$coupon_ids = array_unique( $coupon_ids );

										foreach ( $coupon_ids as $coupon_id ) {

											$title  = get_the_title( $coupon_id );
											
											if ( !$title ) continue;
														
											echo '<option value="'.$coupon_id.'" selected="selected">'. $title .'</option>';
										}
									}
								?>

							</select>
						</p>
					</td>
				</tr>


				<tr>
					<td style="width:20%; vertical-align:top">
						<label for="footer_image"><?php _e( 'Tracking Code', 'woocommerce' ) ?></label>
						    <img class="help_tip" data-tip='<?php _e('If you use third-party statistic trackers you can enter any related code in this field and it will be inserted into each message sent.', 'woocommerce') ?>' 
						    src="<?php echo $this->plugin_url; ?>/help.png" /><br/>

					</td>

					<td style="vertical-align:top; padding-bottom: 5px">

						<p>
						<?php _e( 'Paste in any tracking code you want to include in this message', 'woocommerce' )?>
						<textarea name="followup_tracker_code" style="width:100%; height: 40px;"><?php echo $tracker; ?></textarea>
						</p>

					</td>
				</tr>


			</table>

			<input type="hidden" name="update-followup" value="1" >

		<?php

	}


	function save_post( $post_id ) { 
		global $woocommerce;

		if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
			return;

		if( !current_user_can('edit_post', $post_id) )
			return;

		if ( !isset( $_POST['update-followup'] ) || '1' != $_POST['update-followup'] )
			return;

		update_post_meta( $post_id, 'post_followup_days', absint( $_POST['post_followup_days'] ) );

		update_post_meta( $post_id, 'generate_coupon', $_POST['gen_coupon'] );

		update_post_meta( $post_id, 'restrict_coupon', $_POST['restrict_coupon'] );

		update_post_meta( $post_id, 'followup_type', $_POST['followup_type'] );

		update_post_meta( $post_id, 'send_on_date', trim( $_POST['send_on_date'] ) );

                if ( isset( $_POST['prod_ids'] ) ) {

                        $prod_ids = ( array ) $_POST['prod_ids'];

			$prod_ids = array_unique( $prod_ids );

                        $prod_ids = implode( ',', array_filter( array_map( 'intval', $prod_ids ) ) );
		
                } else {

                        $prod_ids = '';

                }


		update_post_meta( $post_id, 'prod_ids', $prod_ids );


                if ( isset( $_POST['prod_categories'] ) ) {

                        $cat_ids = ( array ) $_POST['prod_categories'];

			$cat_ids = array_unique( $cat_ids );

                        $cat_ids = implode( ',', array_filter( array_map( 'intval', $cat_ids ) ) );
		
                } else {

                        $cat_ids = '';

                }


		update_post_meta( $post_id, 'prod_categories', $cat_ids );


                if ( isset( $_POST['coupon_ids'] ) ) {

                        $prod_ids = ( array ) $_POST['coupon_ids'];

			$prod_ids = array_unique( $prod_ids );

                        $prod_ids = implode( ',', array_filter( array_map( 'intval', $prod_ids ) ) );
		
                } else {

                        $prod_ids = '';
                }

		update_post_meta( $post_id, 'coupon_ids', $prod_ids );

		update_post_meta( $post_id, 'coupon_prefix', trim( $_POST['coupon_prefix'] ) );

		update_post_meta( $post_id, 'tracker_code', trim( $_POST['followup_tracker_code'] ) );

		if ( !isset( $_POST['abandoned_delay'] ) || '' == trim( $_POST['abandoned_delay'] ) )
			$_POST['abandoned_delay'] = 3;

		update_post_meta( $post_id, 'abandoned_delay', trim( $_POST['abandoned_delay'] ) );


		if ( !file_exists( WP_PLUGIN_DIR . '/woocommerce/admin/post-types/writepanels/writepanel-coupon_data.php' ) ) {

			_e( '<strong><em>The required WooCommerce coupon data panel file is missing. This plugin needs an update!</em></strong>', 'woocommerce' );

			die;

		}

		if ( !function_exists( 'woocommerce_coupon_data_meta_box' ) )
			require_once( WP_PLUGIN_DIR . '/woocommerce/admin/post-types/writepanels/writepanel-coupon_data.php' );

		if ( !function_exists( 'woocommerce_coupon_data_meta_box' ) ) { 

			_e( '<strong><em>The required WooCommerce coupon data panel function is missing. This plugin needs an update!</em></strong>', 'woocommerce' );

			die;

		}

		$post = get_post( $post_id );

		woocommerce_process_shop_coupon_meta( $post_id, $post );

	}


	function register_post_type() { 

		if ( current_user_can( 'manage_woocommerce' ) ) 
			$show_in_menu = 'woocommerce'; 
		else 
			$show_in_menu = false;

		register_post_type( "shop_followup",
			    array(
				'labels' => array(
						'name' 		=> __( 'Follow-ups', 'woocommerce' ),
						'singular_name' 	=> __( 'Follow-up', 'woocommerce' ),
						'add_new' 		=> __( 'Add Follow-up', 'woocommerce' ),
						'add_new_item' 	=> __( 'Add New Follow-up', 'woocommerce' ),
						'edit' 		=> __( 'Edit', 'woocommerce' ),
						'edit_item' 	=> __( 'Edit Follow-up', 'woocommerce' ),
						'new_item' 		=> __( 'New Follow-up', 'woocommerce' ),
						'view' 		=> __( 'View Follow-ups', 'woocommerce' ),
						'view_item' 	=> __( 'View Follow-up', 'woocommerce' ),
						'search_items' 	=> __( 'Search Follow-ups', 'woocommerce' ),
						'not_found' 	=> __( 'No Follow-ups found', 'woocommerce' ),
						'not_found_in_trash' => __( 'No Follow-ups found in trash', 'woocommerce' ),
						'parent' 		=> __( 'Parent Follow-up', 'woocommerce' )
					),
				'description' 		=> __( 'This is where you can add new coupons that customers can use in your store.', 'woocommerce' ),
				'public' 		=> true,
				'show_ui'		=> true,
				'capability_type' 	=> 'post',
				'capabilities' => array(
					'publish_posts' 	=> 'manage_woocommerce_coupons',
					'edit_posts' 		=> 'manage_woocommerce_coupons',
					'edit_others_posts' 	=> 'manage_woocommerce_coupons',
					'delete_posts' 		=> 'manage_woocommerce_coupons',
					'delete_others_posts'	=> 'manage_woocommerce_coupons',
					'read_private_posts'	=> 'manage_woocommerce_coupons',
					'edit_post' 		=> 'manage_woocommerce_coupons',
					'delete_post' 		=> 'manage_woocommerce_coupons',
					'read_post' 		=> 'manage_woocommerce_coupons'
				),
				'publicly_queryable' 	=> false,
				'exclude_from_search' 	=> true,
				'show_in_menu' 		=> $show_in_menu,
				'hierarchical' 		=> false,
				'rewrite' 		=> false,
				'query_var' 		=> false,			
				'supports' 		=> array( 'title', 'editor' ),
				'show_in_nav_menus'	=> false,
			    )
		    );
	}


	function edit_coupon_columns($columns){
		
		$columns = array();
		
		$columns["cb"] 		= "<input type=\"checkbox\" />";

		$columns["title"] 	= __("Title", 'woocommerce');

		$columns["delay"] 	= __("Type", 'woocommerce');

		$columns['coupons'] 	= __("Coupons", 'woocommerce');

		$columns["msgs_sent"] 	= __("Sent", 'woocommerce');
		
		$columns["msgs_opened"] = __("Opens", 'woocommerce');

		$columns["msgs_clicked"] = __("Clicks", 'woocommerce');

		$columns["msgs_bounced"] = __("Bounces", 'woocommerce');

		return $columns;
	}


	function custom_coupon_columns($column) {
		global $post, $woocommerce;

		$followup_type = get_post_meta( $post->ID, 'followup_type', true );

		$type 		= get_post_meta($post->ID, 'discount_type', true);

		$amount 	= get_post_meta($post->ID, 'coupon_amount', true);

		$individual_use = get_post_meta($post->ID, 'individual_use', true);

		$product_ids 	= (get_post_meta($post->ID, 'prod_ids', true)) ? explode(',', get_post_meta($post->ID, 'prod_ids', true)) : array();

		$cat_ids 	= (get_post_meta($post->ID, 'prod_categories', true)) ? explode(',', get_post_meta($post->ID, 'prod_categories', true)) : array();

		$usage_limit 	= get_post_meta($post->ID, 'usage_limit', true);

		$expiry_date 	= get_post_meta($post->ID, 'expiry_date', true);

		$prod_ids 	= ( get_post_meta( $post->ID, 'prod_ids', true ) ) ? explode(',', get_post_meta( $post->ID, 'prod_ids', true ) ) : array();

		$cat_ids 	= ( get_post_meta( $post->ID, 'prod_categories', true ) ) ? explode(',', get_post_meta( $post->ID, 'prod_categories', true ) ) : array();

		switch ( $column ) {
			case "delay" :

				if ( 'abandoned' == $followup_type ) { 

				    $abandoned_delay = get_post_meta( $post->ID, 'abandoned_delay', true);

				    _e( 'Abandoned Carts', 'woocommerce' ); 

				    echo '<br/>';

				    _e( 'After', 'woocommerce' );

				    echo ' ' . $abandoned_delay . ' ';

				    _e( 'days', 'woocommerce' );
				}

				if ( 'buyer' == $followup_type ) { 

				    $delay 	= get_post_meta( $post->ID, 'post_followup_days', true);

				    _e( 'Buyers after', 'woocommerce' ); 

				    echo ' ' . $delay . ' ';

				    _e( 'days', 'woocommerce' );
				}

				if ( 'on_date' == $followup_type ) {
 
				    $send_on_date = get_post_meta( $post->ID, 'send_on_date', true );

				    _e( 'Everyone on ', 'woocommerce' );

				    echo $send_on_date;
				}

				if ( 'every_anniversary' == $followup_type ) { 
				    _e( 'Everyone on anniversary', 'woocommerce' );
				}

				if ( 'first_anniversary' == $followup_type ) { 
				    _e( 'Customer\'s first anniversary', 'woocommerce' );
				}

				if ( sizeof( $prod_ids ) > 0 || sizeof( $cat_ids ) > 0 ) {

					echo '<br/>';
					_e( 'When purchase includes:', 'woocommerce' );

				}

				if ( sizeof( $prod_ids ) > 0 ) {

					foreach( $prod_ids as $p ) { 

						$title  = get_the_title( $p );

						$sku    = get_post_meta( $p, '_sku', true );

						if ( !$title ) continue;

						if ( isset( $sku ) && $sku ) $sku = ' (SKU: ' . $sku . ')';

						echo '<br/>'.$title . $sku;

					}
				}

				if ( sizeof( $cat_ids ) > 0 ) {

					$categories = get_terms( 'product_cat', 'orderby=name&hide_empty=0' );

					if ( $categories ) foreach ( $categories as $cat )
						echo '<br/>' . $cat->name . ' - (' . __('cat#','woocommerce' ) . $cat->term_id . ')';

				}

				break;

			case "coupons" :

				echo $woocommerce->get_coupon_discount_type( $type ) . '<br/>' .
				    __( 'Amount: ', 'woocommerce' ) . $amount  . '<br/>' .
				    __( 'Products: ', 'woocommerce' ) . implode( ', ', $product_ids) . '<br/>' .
				    __( 'Cats: ', 'woocommerce' ). implode( ', ', $cat_ids) . '<br/>' .
				    __( 'Limit: ', 'woocommerce' ) . $usage_limit  . '<br/>' .
				    __( 'Used: ', 'woocommerce' ) . $usage_count . '<br/>' .
				    __( 'Expires: ', 'woocommerce' ) . $expiry_date . '<br/>' ;

				break;

			case 'msgs_sent' :
				echo get_post_meta( $post->ID, 'messages_sent' , true );
				break;

			case 'msgs_opened' :
				echo get_post_meta( $post->ID, 'messages_opened' , true );
				break;

			case 'msgs_clicked' :
				echo get_post_meta( $post->ID, 'messages_clicked' , true );
				break;

			case 'msgs_bounced' :
				echo get_post_meta( $post->ID, 'messages_bounced' , true );

				break;

		}
	}


	function shop_followup_sortable_columns( $columns ) {

		$columns['msgs_opened'] = 'opens';

		$columns['msgs_sent'] = 'sent';

		$columns['msgs_clicked'] = 'clicks';

		return $columns;
	}


	function shop_followup_column_sorting( $vars ){

		if ( !isset( $vars['orderby'] ) )
			return $vars;

		switch( $vars['orderby'] ) { 

			case 'sent' : 
					$vars = array_merge( $vars, array(
									'meta_key' => 'messages_sent',
									'orderby'  => 'meta_value'
								    ) 
							);
				break;

			case 'opens' : 
					$vars = array_merge( $vars, array(
									'meta_key' => 'messages_opened',
									'orderby'  => 'meta_value'
								    ) 
							);
				break;

			case 'clicks' : 
					$vars = array_merge( $vars, array(
									'meta_key' => 'messages_clicked',
									'orderby'  => 'meta_value'
								    ) 
							);
				break;
		}

		return $vars;
	}


	function iw_side() { 
	?>
		<div style="width:250px; border: 3px solid #00cc00; padding: 12px 0; font-weight:bold; font-style:italic; margin-top: 15px; text-align:center; border-radius:7px;-webkit-border-radius:7px">
			<a title=" More Extensions + Custom WooCommerce Site Development " href="http://ignitewoo.com" target="_blank" style="color:#0000cc; text-decoration:none">
			    <img style="height:50px" src="%3D%3D">
			</a>
			<br>
			Get more custom plugins <br/> + Custom development
			<br><br>
			<a title=" More Plugins + Custom WooCommerce Site Development " href="http://ignitewoo.com" target="_blank" style="color:#0000cc; text-decoration:none">Contact us<br><br/>Visit IgniteWoo.com!</a>
		</div>
	<?php
	}


	function activation() {
		global $wpdb;

		wp_schedule_event( time(), 'hourly', array( &$this, 'hourly_event' ) );

		wp_schedule_event( time(), 'daily', array( &$this, 'daily_event' ) );


		$sql = 'select ID from ' . $wpdb->posts . ' where post_type="shop_order" ';

		$res = $wpdb->get_results( $sql, ARRAY_A );

		if ( !$res ) 
			return;

		foreach( $res as $o ) { 
			if ( !get_post_meta( $o['ID'], 'follow_ups', true ) )
				update_post_meta( $o['ID'], 'follow_ups', 0 );
		}

		if ( !get_option( 'woocommerce_followup_title', false ) ) 
			update_option( 'woocommerce_followup_title', __( 'Unsubscribe', 'woocommerce' ) );

		if ( !get_option( 'woocommerce_followup_body', false ) ) 
			update_option( 'woocommerce_followup_title', __( 'Your unsubscribe request has been processed. Thanks for shopping with us!', 'woocommerce' ) );

	}


	function do_hourly() {
		global $wpdb, $post, $woocommerce; 

		if ( !$woocommerce ) 
			return;

		// make sure there's a mailer instance ready
		$woocommerce->mailer();

		// get all published shop_followup posts and process them
		query_posts( array( 'post_type' => 'shop_followup', 'post_status' => 'publish' ) );

		if ( have_posts() ) { 

			// Load skip table
			if ( !$this->skips ) 
				$this->skips = get_option( 'ignite_followup_ignore', false );

			while ( have_posts()  ) { 

				set_time_limit(0);

				the_post(); 

				$message = wpautop( $post->post_content );

				$subject = get_the_title();

				$meta = get_post_custom( $post->ID, true );

				if ( !$meta ) 
					continue;

				// check type and process accordingly

				switch( $meta['followup_type'][0] ) { 

					case 'buyer' :

						if ( absint( $meta['post_followup_days'][0] ) > 0 )
							$this->to_buyers( $post->ID, $meta, $subject, $message );

						break;

					case 'on_date': 
 
						$time = time();
						$today = date( 'm', $time ) . '-' . date( 'd', $time );

						if ( '' != trim( $meta['send_on_date'][0] ) && ( $today == trim( $meta['send_on_date'][0] ) ) )
							$this->on_date( $post->ID, $meta, $subject, $message );

						break;

					case 'every_anniversary': 

						$this->anniversary( $post->ID, $meta, $subject, $message, 'every' );
						break;


					case 'first_anniversary': 

						$this->anniversary( $post->ID, $meta, $subject, $message, 'first' );
						break;

					case 'abandoned' : 

						$this->abandoned( $post->ID, $meta, $subject, $message );
						break;
				}

				set_time_limit(0);
 
			}

		}

		$this->current_msg = false;

		rewind_posts();


		// Delete records of abandoned carts older than 14 days

		$carts = get_option( 'ignite_abandoned_carts', false );

		if ( !$carts || is_array( $carts ) || count( $carts ) <= 0 )
			return;

		$abandoned_cleanup_delay = get_option( 'abandoned_cleanup_delay', false );

		if ( !$abandoned_cleanup_delay ) 
			$abandoned_cleanup_delay = 14;

		$interval = 60 * 60 * 24 * $abandoned_cleanup_delay; // 14 days

		foreach( $carts as $key => $val ) { 

			if ( ( time() - $val['timestamp' ] ) > $interval ) { 

				unset( $carts[ $key ] );

				delete_option( 'ignite_cart_' . $val['user'] );

			}

		}

		$carts = array_values( $carts );

		update_option( 'ignite_abandoned_carts', $carts );

		return;

	}


	function do_daily() {
		global $wpdb;

		$sql = 'select ID, m1.meta_value as t, m2.meta_value as d from ' . $wpdb->posts . ' 
			left join ' . $wpdb->postmeta . ' m1 on ID = m1.post_id
			left join ' . $wpdb->postmeta . ' m2 on ID = m2.post_id 
			where 
			post_type="shop_followup" and 
			m1.meta_key="followup_type" and m1.meta_value="on_date" and 
			m2.meta_key="send_on_date" and m2.meta_value != "" ';

		$msgs = $wpdb->get_results( $sql, ARRAY_A );

		if ( !$msgs ) 
			return;

                $today = gmdate( 'm-d', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );

		foreach( $msgs as $key => $msg ) { 

			if ( $msg['d'] == $today )
				continue;

			$sql = 'select ID from ' . $wpdb->posts . ' left join ' . $wpdb->postmeta . ' on ID = post_id
				where 
				post_type="shop_order" and 
				meta_key="follow_ups" and FIND_IN_SET( ' . $msg['ID'] . ', meta_value ) != 0';

			$oids = $wpdb->get_results( $sql, ARRAY_A );

			if ( !$oids )
				continue; 

			foreach( $oids as $o ) { 

				$followup_ids = get_post_meta( $o['ID'], 'follow_ups', true );

				if ( !$followup_ids )
					continue;

				$followup_ids = explode( ',' , $followup_ids );

				foreach( $followup_ids as $key => $f ) {

					if ( $f == $msg['ID'] )
						unset( $followup_ids[ $key ] );

				}

				update_post_meta( $msg['ID'], 'follow_ups', $followup_ids );

			}

			unset( $oids );

		}

		unset( $msgs );

	}


	function filter_tags( $msg = '', $coupon_code = false, $to = '', $fname = '', $lname = '' ) { 

		if ( !$msg || '' == $msg ) 
			return;


		if ( '' != $fname ) 
			$msg = str_replace( '{first_name}', $fname, $msg );
		else 
			$msg = str_replace( '{first_name}', '', $msg );


		if ( '' != $lname ) 
			$msg = str_replace( '{last_name}', $lname, $msg );
		else 
			$msg = str_replace( '{last_name}', '', $msg );


		if ( '' != $to ) 
			$msg = str_replace( '{customer_email}', $to, $msg );
		else
			$msg = str_replace( '{customer_email}', '', $msg );


		if ( false !== $coupon_code ) 
			$msg = str_replace( '{coupon_code}', $coupon_code, $msg );
		else 
			$msg = str_replace( '{coupon_code}', '', $msg );


		$msg = str_replace( '{site_name}', get_bloginfo('sitename'), $msg );

		$msg = str_replace( '{site_url}', get_bloginfo('home'), $msg );

		return wpautop( $msg );

	}


	function generate_coupon( $meta = '', $restrict = false, $to = '' ) { 
		global $wpdb;

		if ( '' == trim( $meta['coupon_prefix'][0] ) )
			$prefix = strtoupper( date( 'My', time() ) ) . '-';
		else
			$prefix = trim( $meta['coupon_prefix'][0] );

		$title = uniqid( $prefix );

		$sql = 'select ID from ' . $wpdb->posts . ' where post_title = "%s" ';

		$sql = $wpdb->prepare( $sql, $title );

		$exists = $wpdb->get_var( $sql );

		while( $exists ) { 

			$title = uniqid( $prefix );

			$sql = 'select ID from ' . $wpdb->posts . ' where post_title = "%s" ';

			$sql = $wpdb->prepare( $sql, $title );

			$exists = $wpdb->get_var( $sql );

		}

		$args = array( 
			    'post_title' => $title,
			    'post_type' => 'shop_coupon',
			    'post_content' => '',
			    'post_status' => 'publish',
			    'post_author' => 1
			);

		$post_id = wp_insert_post( $args );

		if ( !$post_id ) 
			return false;

		$post = get_post( $post_id );

		$_POST = array();

		$_POST['discount_type'] = $meta['discount_type'][0];

		$_POST['coupon_amount'] = $meta['coupon_amount'][0];

		$_POST['individual_use'] = $meta['individual_use'][0];

		$_POST['product_ids'] = $meta['product_ids'][0];

		$_POST['exclude_product_ids'] = $meta['exclude_product_ids'][0];

		$_POST['usage_limit'] = $meta['usage_limit'][0];

		$_POST['expiry_date'] = $meta['expiry_date'][0];

		$_POST['apply_before_tax'] = $meta['apply_before_tax'][0];

		$_POST['free_shipping'] = $meta['free_shipping'][0];

		$data = maybe_unserialize( $meta['product_categories'][0] );

		if ( is_array( $data ) )
			foreach( $data as $d ) 
				$_POST['product_categories'][] = $d;

		$data = maybe_unserialize( $meta['exclude_product_categories'][0] );

		if ( is_array( $data ) )
			foreach( $data as $d ) 
				$_POST['exclude_product_categories'][] = $d;

		$_POST['minimum_amount'] = $meta['minimum_amount'][0];

		if ( $restrict ) 
			$_POST['customer_email'] = $to;
		else
			$_POST['customer_email'] = '';


		if ( !file_exists( WP_PLUGIN_DIR . '/woocommerce/admin/post-types/writepanels/writepanel-coupon_data.php' ) ) {

			_e( '<strong><em>The required WooCommerce coupon data processing file is missing. This plugin needs an update!</em></strong>', 'woocommerce' );

			die;

		}

		if ( !function_exists( 'woocommerce_process_shop_coupon_meta' ) )
			require_once( WP_PLUGIN_DIR . '/woocommerce/admin/post-types/writepanels/writepanel-coupon_data.php' );

		if ( !function_exists( 'woocommerce_process_shop_coupon_meta' ) ) { 

			_e( '<strong><em>The required WooCommerce coupon data processing function is missing. This plugin needs an update!</em></strong>', 'woocommerce' );

			die;

		}

		woocommerce_process_shop_coupon_meta( $post_id, $post );

		return $title; 

	}


	function check_purchase_details( $products, $categories, $order_id ) { 

		$good = false;

		$order = new WC_Order( $order_id ); 

		if ( !$order ) 
			return false;

		$order_items = (array) $order->get_items();

		if ( sizeof( $products ) > 0 )
			$product_ids = explode( ',' , $products );

		if ( sizeof( $categories ) > 0 )
			$cat_ids = explode( ',' , $categories );

		if ( count( $product_ids ) > 0 || count( $cat_ids ) > 0 ) 
		foreach( $order_items as $item ) { 
			
			$product = $order->get_product_from_item( $item );

			if ( count( $product_ids ) > 0 )  { 

				if ( is_a( $product, 'WC_Product_Variation' ) )
					if ( in_array( $product->variation_id, $product_ids ) )
						$good = true;

				if ( in_array( $product->id, $product_ids ) )
					$good = true;

			}

			if ( count( $cat_ids ) > 0 ) {

				$terms = wp_get_post_terms( $product->id, 'product_cat' );

				$prod_cats = array(); 

				foreach ( $terms as $term ) 
					$prod_cats[] = $term->term_id;

				if ( count( $prod_cats ) > 0 ) 
					foreach( $prod_cats as $c ) 
						if ( in_array( $c->id, $cat_ids ) )
							$good = true;

			}
		}

		return $good; 

	}


	function to_buyers( $id, $meta = '', $subject = '', $message = '' ) { 
		global $woocommerce, $wpdb;

		if ( !$woocommerce ) 
			return;

		if ( !$meta || '' == $meta ) 
			return;

		if ( !$subject || '' == $subject ) 
			return;

		if ( !$message || '' == $message ) 
			return;

		$days = absint( $meta['post_followup_days'][0] );

		if ( $days <= 0 ) 
			return;

		$sql = 'select distinct ID from ' . $wpdb->posts . ' p left join ' . $wpdb->postmeta . ' m1 on p.ID = m1.post_id 
			left join ' . $wpdb->postmeta . ' m2 on p.ID = m2.post_id 
			WHERE post_type = "shop_order" AND 
			( m1.meta_key = "_completed_date" and m1.meta_value != "" ) AND 
			( m1.meta_key = "_completed_date" AND DATEDIFF(  CURDATE(), CAST( m1.meta_value AS DATE ) ) >= '. $days . ' ) AND 
			( m2.meta_key = "follow_ups" AND FIND_IN_SET( ' . $id . ', m2.meta_value ) = 0 )';

		$orders = $wpdb->get_results( $sql, ARRAY_A );

		if ( is_array( $orders ) and count ( $orders ) > 0 ) {
			foreach( $orders as $o ) { 

				$this->send_it( $id, $o['ID'], $meta, $message, $subject );

				set_time_limit(0);

			}
		}

	}


	function on_date( $id, $meta = '', $subject = '', $message = '' ) { 
		global $woocommerce, $wpdb;

		if ( !$woocommerce ) 
			return;

		if ( !$meta || '' == $meta ) 
			return;

		if ( !$subject || '' == $subject ) 
			return;

		if ( !$message || '' == $message ) 
			return;

		$month_day =  get_post_meta( $id, 'send_on_date', true ); // 7-29

                $today = gmdate( 'm-d', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );

		if ( $today != $month_day ) 
			return;

		$sql = 'select distinct ID from ' . $wpdb->posts . ' p left join ' . $wpdb->postmeta . ' m1 on p.ID = m1.post_id 
			left join ' . $wpdb->postmeta . ' m2 on p.ID = m2.post_id 
			WHERE post_type = "shop_order" AND 
			( m1.meta_key = "_completed_date" and m1.meta_value != "" ) AND
			( m2.meta_key = "follow_ups" AND FIND_IN_SET( ' . $id . ', m2.meta_value ) = 0 )';

		$orders = $wpdb->get_results( $sql, ARRAY_A );

		if ( is_array( $orders ) and count ( $orders ) > 0 ) {

			foreach( $orders as $o ) { 

				$this->send_it( $id, $o['ID'], $meta, $message, $subject );

				set_time_limit(0);

			}

		}
	}


	function anniversary( $id, $meta = '', $subject = '', $message = '', $type = '' ) { 
		global $woocommerce, $wpdb;

		if ( !$woocommerce ) 
			return;

		if ( !$meta || '' == $meta ) 
			return;

		if ( !$subject || '' == $subject ) 
			return;

		if ( !$message || '' == $message ) 
			return;

                $today = gmdate( 'm-d', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );

		if ( 'every' == $type ) { 

			$sql = 'select distinct m3.meta_value as email, m1.meta_value as completed, p.ID from ' . $wpdb->posts . ' p left join ' . $wpdb->postmeta . ' m1 on p.ID = m1.post_id 
				left join ' . $wpdb->postmeta . ' m2 on p.ID = m2.post_id 
				left join ' . $wpdb->postmeta . ' m3 on p.ID = m3.post_id 
				WHERE post_type = "shop_order" AND 
				( m1.meta_key = "_completed_date" and m1.meta_value != "" ) AND 
				( m1.meta_key = "_completed_date" AND "' . $today . '" = DATE_FORMAT( m1.meta_value, "%m-%d" ) ) AND 
				( m2.meta_key = "follow_ups" AND FIND_IN_SET( ' . $id . ', m2.meta_value ) = 0 ) AND
				( m3.meta_key = "_billing_email" AND m3.meta_value != "" ) 
				';

			$orders = $wpdb->get_results( $sql, ARRAY_A );
		}


		if ( 'first' == $type ) { 

			$sql = 'select distinct m3.meta_value as email, m1.meta_value as completed, p.ID from ' . $wpdb->posts . ' p left join ' . $wpdb->postmeta . ' m1 on p.ID = m1.post_id 
				left join ' . $wpdb->postmeta . ' m2 on p.ID = m2.post_id 
				left join ' . $wpdb->postmeta . ' m3 on p.ID = m3.post_id 
				WHERE post_type = "shop_order" AND 
				( m1.meta_key = "_completed_date" and m1.meta_value != "" ) AND 
				( m1.meta_key = "_completed_date" AND "' . $today . '" = DATE_FORMAT( m1.meta_value, "%m-%d" ) ) AND 
				( m2.meta_key = "follow_ups" AND FIND_IN_SET( ' . $id . ', m2.meta_value ) = 0 ) AND
				( m3.meta_key = "_billing_email" AND m3.meta_value != "" ) 
				order by CAST( m3.meta_value AS DATE) ASC';

			$orders = $wpdb->get_results( $sql, ARRAY_A );

			$cid = '';

			$first_orders = array();

			// sort out the first order for each unique customer - where a unique customer means a unique email address
			if ( $orders ) {

				foreach( $orders as $o ) { 

					if ( $cid != $o ) { 

						$first_orders[] = $o;

						$cid = $o['email'];

					}

				}

			}

			$orders = $first_orders; 

		}


		if ( is_array( $orders ) and count ( $orders ) > 0 ) 
			foreach( $orders as $o ) { 

				$this->send_it( $id, $o['ID'], $meta, $message, $subject );

				set_time_limit(0);

			}

	}


	function abandoned( $id, $meta = '', $subject = '', $message = '' ) { 
		global $woocommerce;

		if ( !$meta || '' == $meta ) 
			return;

		if ( !$subject || '' == $subject ) 
			return;

		if ( !$message || '' == $message ) 
			return;

		$carts = get_option( 'ignite_abandoned_carts', false );

		if ( !$carts ) 
			return;

		if ( !is_array( $carts ) ) 
			return;

		$delay = get_post_meta( $id, 'abandoned_delay', false );

		if ( !$delay ) 
			$delay = 3;

		$interval = 60 * 60 * 24 * $delay; 

		foreach ( $carts as $key => $cart ) { 

			$stamp = $cart['timestamp'];

			if ( !$stamp )
				continue;

			$user = $cart['user']; 

			if ( !$user ) 
				continue;

			$userdata = get_userdata( $user );

			if ( !$userdata || is_wp_error( $userdata ) || ( isset( $userdata->data->user_email ) && !is_email( $userdata->data->user_email ) ) )
				continue;

			if ( ( time() - $stamp ) < $interval )
				continue;

			// maybe send a message

			if ( false !== strpos( $message, '{cart_contents}' ) ) {

				if ( isset( $woocommerce->cart_contents) ) 
					$saved_woo = $woocommerce->cart_contents; 
				else
					$saved_woo = false;

				if ( !class_exists( 'WC_Cart' ) )
					require_once( WP_PLUGIN_DIR . '/woocommerce/classes/class-wc-cart.php' );

				if ( !class_exists( 'WC_Customer' ) )
					require_once( WP_PLUGIN_DIR . '/woocommerce/classes/class-wc-customer.php' );

				$woocommerce->customer = new WC_Customer();

				$woocommerce->cart = get_option( 'ignite_cart_'. $cart['user'] );

				if ( !is_array( $woocommerce->cart ) && !is_object( $woocommerce->cart ) )
					continue;

				if ( sizeof( $woocommerce->cart->get_cart() ) <= 0 ) 
					continue;

				$cart_items[] = array();

				foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {

					$_product = $values['data'];

					if ( !$_product->exists() || $values['quantity'] <= 0 )
						continue;

					if ( $_product->is_sold_individually() ) {

						$product_quantity = '1';

					} else {

						$data_min = apply_filters( 'woocommerce_cart_item_data_min', '', $_product );

						$data_max = ( $_product->backorders_allowed() ) ? '' : $_product->get_stock_quantity();

						$data_max = apply_filters( 'woocommerce_cart_item_data_max', $data_max, $_product ); 
						
						$product_quantity = esc_attr( $values['quantity'] );
					}

					$cart_items[] = array(
							'name' => sprintf('<a href="%s">%s</a>', esc_url( get_permalink( apply_filters('woocommerce_in_cart_product_id', $values['product_id'] ) ) ), apply_filters('woocommerce_in_cart_product_title', $_product->get_title(), $values, $cart_item_key ) ),
							'price' => get_option('woocommerce_display_cart_prices_excluding_tax') == 'yes' || $woocommerce->customer->is_vat_exempt() ? $_product->get_price_excluding_tax() : $_product->get_price(),
							'qty' => apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key ),
							'item_total' => apply_filters( 'woocommerce_cart_item_subtotal', $woocommerce->cart->get_product_subtotal( $_product, $values['quantity'] ), $values, $cart_item_key ),
					);

				}

				if ( $saved_woo )
					$woocommerce->cart_contents = $saved_woo; 

			}

			$this->send_it( $id, 0, $meta, $message, $subject, $userdata, false, array_filter( $cart_items ) );

			set_time_limit(0);
		}

	}


	function send_it( $id, $order_id, $meta, $message, $subject, $user = '', $cart_check = true, $items = false ) { 
		global $woocommerce;


		if ( !$this->skips ) 
			$this->skips = get_option( 'ignite_followup_ignore', false );

		if ( !$this->skips ) 
			$this->skips = array();

		if ( $cart_check ) { 

			$products = get_post_meta( $id, 'prod_ids', true );

			$cats = get_post_meta( $id, 'prod_categories', true );

			// check if the message requires specific products or categories
			if ( sizeof( $products ) > 0 || sizeof( $cats ) > 0 ) { 

				if ( !$this->check_purchase_details( $products, $cats, $order_id ) )
					return;

			}

		}

		if ( $user ) { 

			$to = $user->data->user_email; 

			$fname = get_user_meta( $user->data->ID, 'billing_first_name', true );

			$lname = get_user_meta( $user->data->ID, 'billing_last_name', true );

		} else { 

			$order_meta = get_post_custom( $order_id );

			$to = trim( $order_meta['_billing_email'][0] );

			$fname = trim( $order_meta['_billing_first_name'][0] );

			$lname = trim( $order_meta['_billing_last_name'][0] );
		} 

		if ( '' == $to ) 
			return;

		if ( in_array( $to, $this->skips ) )
			return;


		// maybe generate a coupon code
		$coupon_code = '';

		if ( '1' == get_post_meta( $id, 'restrict_coupon', true ) )
			$restrict = true; 
		else 
			$restrict = false;


		if ( '1' == $meta['generate_coupon'][0] )
			$coupon_code = $this->generate_coupon( $meta, $restrict, $to );


		$coupon_ids = get_post_meta( $id, 'coupon_ids', true );

		if ( $coupon_ids ) { 

			$coupons = explode( ',', $coupon_ids );

			foreach( $coupons as $c ) 

			    $coupon_code .= '<br/>' . get_the_title( $c );

		}

		$this->current_msg = $id; 

		// replace {tags} in the content
		$message = $this->filter_tags( $message, $coupon_code, $to, $fname, $lname ); 

		$pattern = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#';

                $message = preg_replace_callback( $pattern, array( &$this, 'add_clicktrack' ), $message );

		if ( !$woocommerce->woocommerce_email ) 
			$woocommerce->mailer();

		$this->email_recipient = $to; 

		$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

		$subject = sprintf( __( '[%s] %s', 'woocommerce' ), $blogname, $subject );

		global $cart_items, $followup_content, $email_heading;

		$cart_items = $items;

		$followup_content = $message; 

		$email_heading = $subject;

		$this->is_followup = true;

		ob_start();

		if ( $cart_check ) 
			$template_name = 'emails/followup_email_template.php';
		else
			$template_name = 'emails/abandoned_cart.php';

		$default_path = dirname( __FILE__ ) . '/';
		
		$located = woocommerce_locate_template( $template_name, $template_path, $default_path );

		if ( $located ) { 

			do_action( 'woocommerce_before_template_part', $template_name, '', $located );

			require( $located );

			do_action( 'woocommerce_after_template_part', $template_name, '', $located );

		} else {

			ob_end_clean();

			return;

		}

		$msg = ob_get_clean();

		$this->is_followup = false;

		// Queue additional mail envelope headers
		$headers = apply_filters('woocommerce_email_headers', '', 'followup_message');

		$woocommerce->woocommerce_email->send( $to, $subject, $message, $headers );

		// should be a string of post IDs like this:  1,2,3,4,5
		$followup_ids = get_post_meta( $order_id, 'follow_ups', true );

		if ( false !== $followup_ids && '' == $followup_ids ) 
			$followup_ids = $id;
		else 
			$followup_ids .= ',' . $id;

		update_post_meta( $order_id, 'follow_ups', $followup_ids );

		$msgs_sent = get_post_meta( $id, 'messages_sent' , true );

		if ( !$msg_sent )
			$msgs_sent = 1;
		else
			$msgs_sent++; 

		update_post_meta( $id, 'messages_sent', $msgs_sent );

	}


	function add_clicktrack( $matches ) {

		if ( !is_array( $matches ) || !isset( $matches[0] ) )
			return $matches;

		$url = trailingslashit( $matches[0] );

		if ( false !== strpos( '?', $url  ) ) 
			$url .= '?ignclick=' . base64_encode( $this->current_msg );
		else
				$url .= '&ignclick=' . base64_encode( $this->current_msg );

		return $url;

	}


	function build_mail_footer( $txt = '' ) { 

		if ( !$this->is_followup ) 
			return;

		$footer = get_option( 'woocommerce_followup_footer', false );

		$hash = sha1( $this->email_recipient );

		$tracker = get_post_meta( $post->ID, 'tracker_code', true );

		if ( $tracker ) 
			$txt .= $tracker;

		$txt .= '
				<table width="600" cellspacing="0" cellpadding="10" border="0" id="templateFooter">
					<tbody><tr>
						<td valign="top" class="footerContent">
						<table width="100%" cellspacing="0" cellpadding="10" border="0">
						    <tbody><tr>
							<td valign="middle" style="border:0; color:#969696; font-family:Arial; font-size:12px; line-height:125%; text-align:center;" id="credit" colspan="2">
								<p>' . $footer . '</p>';

								$txt .= '<p><a href="' . get_option( 'home' ) . '/?followup_unsubsubscribe=' . $hash . '">' . __( 'Unsubscribe from these messages', 'woocommerce' ) . '</a></p>';

								$txt .= '<img src="' . get_option( 'home' ) . '/?followup_img=' . $this->current_msg . '" style="width:5px; height:5px">';

		$txt .= '				</td>
						    </tr>
						    
						</tbody></table>
					    </td>
					</tr>
				    </tbody></table>
			';




		echo $txt;

	}


	function followup_img() { 
		global $wpdb;

		if ( !isset( $_GET['followup_img'] ) || '' == $_GET['followup_img'] )
			return;

		if ( absint ( $_GET['followup_img'] ) <= 0 )
			return;

		$id = absint( $_GET['followup_img'] );

		$sql = 'select post_type from ' . $wpdb->posts . ' where ID = "%s"';

		$sql = $wpdb->prepare( $sql, $id );

		$res = $wpdb->get_var( $sql );

		if ( !$res || 'shop_followup' != $res ) 
			return;

		if ( file_exists( dirname( __FILE__ ) . '/followup_img.png' ) ) {

			$opens = get_post_meta( $id, 'messages_opened', true );

			if ( !$opens ) 
				$opens = 1;
			else
				$opens++;

			update_post_meta( $id, 'messages_opened', $opens );

			$img = imagecreatefrompng( dirname( __FILE__ ) . '/followup_img.png' );

			header('Content-Type: image/png');

			imagepng( $img );

			die;

		}

	}


	function followup_clk() { 
		global $wpdb;

		if ( !isset( $_GET['ignclick'] ) || '' == $_GET['ignclick'] )
			return;

		$click = base64_decode( $_GET['ignclick'] );

		if ( !$click ) 
			return;

		if ( absint ( $click ) <= 0 )
			return;

		$id = absint( $click );

		$sql = 'select post_type from ' . $wpdb->posts . ' where ID = "%s"';

		$sql = $wpdb->prepare( $sql, $id );

		$res = $wpdb->get_var( $sql );

		if ( !$res || 'shop_followup' != $res ) 
			return;

		$cnt = get_post_meta( $id, 'messages_clicked', true );

		if ( !$cnt ) 
			$cnt = 1;
		else
			$cnt++;

		update_post_meta( $id, 'messages_clicked', $cnt );

	}


	function handle_unsubs() { 
		global $wpdb;

		if ( !isset( $_GET['followup_unsubsubscribe'] ) || '' == $_GET['followup_unsubsubscribe'] )
			return;

		$hash = trim( $_GET['followup_unsubsubscribe'] ); 

		$sql = 'select user_email from '. $wpdb->users  .' where sha1 ( user_email ) = "%s"';

		$sql = $wpdb->prepare( $sql, $hash );

		$res = $wpdb->get_var( $sql );

		if ( !$res ) 
			return;

		$skips = get_option( 'ignite_followup_ignore', false );

		if ( !$skips ) 
			$skips = array();

		if ( !in_array( $res, $skips ) ) { 

			$skips[] = $res;

			update_option( 'ignite_followup_ignore', $skips );

			get_header();

			echo '<h2>' . get_option( 'woocommerce_followup_title', false ) . '</h2>';

			echo '<div style="margin: 15px">' . wpautop( get_option( 'woocommerce_followup_body', false ) ) . '</div>';

			get_footer();

			die;
		}

	}


	function add_followup_meta( $order_id ) { 
		global $user_ID; 

		update_post_meta( $order_id, 'follow_ups', 0 );

		get_currentuserinfo();

		if ( !is_user_logged_in() ) 
			return;

		$carts = get_option( 'ignite_abandoned_carts', false );

		if ( !$carts ) 
			return;

		foreach( $carts as $key => $val )
			if ( $user_ID == $val['user'] ) 
				unset( $carts[ $key ] );

		$carts = array_values( $carts );

		update_option( 'ignite_abandoned_carts', $carts );

		delete_option( 'ignite_cart_'. $user_ID );

	}


	function add_to_cart() { 
		global $user_ID, $woocommerce;

		get_currentuserinfo();

		if ( !$user_ID ) 
			return;

		if ( !isset( $woocommerce->cart->cart_contents ) )
			return;

		$woocommerce->cart->calculate_totals();

		update_option( 'ignite_cart_' . $user_ID, $woocommerce->cart );

		$carts = get_option( 'ignite_abandoned_carts', false );

		if ( !$carts ) 
			$carts = array();

		foreach( $carts as $key => $val )
			if ( $user_ID == $val['user'] ) 
				unset( $carts[ $key ] );

		$carts = array_values( $carts );

		$carts[] = array( 'timestamp' => time(), 'user' => $user_ID );

		update_option( 'ignite_abandoned_carts', $carts );

	}

}

$woocommerce_post_sale_followup = new woocommerce_post_sale_followup();

register_activation_hook( __FILE__, array( $woocommerce_post_sale_followup, 'activation' ) );
?>